define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxVulnerabilityArea";

    var fxVulnerabilityAreaFormHtml = sysPath + "/views/fxVulnerabilityAreaForm.html";
    var getFxVulnerabilityAreaController = function () {
        return getServer() + "/fx/fxVulnerabilityAreas";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initAreaSelect();
        //initStructureTypeSelect();
        //initDamageDegreeSelect();

    };

    // 初始化搜索栏
    var initAreaSelect = function () {
        $.ajax({
            url: getFxVulnerabilityAreaController() + "/getValidDictItemsByDictCode/" + "area",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("areaSelect");
                //mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
                $("#areaSelect").val("华北");
                createFxVulnerabilityAreaGrid();
            }
        });
    };

    var initAreaSelectFrom = function () {
        $.ajax({
            url: getFxVulnerabilityAreaController() + "/getValidDictItemsByDictCode/" + "area",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("area");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initStructureTypeSelectFrom = function () {
        $.ajax({
            url: getFxVulnerabilityAreaController() + "/getValidDictItemsByDictCode/" + "structureType",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("structureType");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initDamageDegreeSelectFrom = function () {
        $.ajax({
            url: getFxVulnerabilityAreaController() + "/getValidDictItemsByDictCode/" + "damageDegree",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("damageDegree");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initEarthquakeIntensitySelectFrom = function () {
        $.ajax({
            url: getFxVulnerabilityAreaController() + "/getValidDictItemsByDictCode/" + "earthquakeIntensity",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("earthquakeIntensity");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
        	if(!$("#areaSelect").val()){
        		Util.alert("请选择地区");
                return;
        	}
            createFxVulnerabilityAreaGrid();
        });
        $("#btnReset").click(function () {
            $("#areaSelect").val("华北");
            createFxVulnerabilityAreaGrid();
        });
    };
    var createFxVulnerabilityAreaGrid = function () {
        $("#fxVulnerabilityAreaGrid").datagrid({
            url: getFxVulnerabilityAreaController() + "/listFxVulnerabilityAreas",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
//          fit:true,
//          striped: true,
            rownumbers: false,
            columns: [[
//              {field: "ck", checkbox: true},
                {
                    field: 'area',
                    title: '地区',
                    rowspan: 2,
                    width: '16.6%',
                    align: 'center',
                },
                {
                    field: 'structureType',
                    title: '结构类型',
                    rowspan: 2,
                    width: '16.6%',
                    align: 'center',
                },
                {
                    field: 'damageDegree',
                    title: '破坏程度',
                    rowspan: 2,
                    width: '16.6%',
                    align: 'center',
                    formatter: function (value) {
                        if (value == "0") {
                            return '基本完好';
                        } else if (value == "1") {
                            return '轻微破坏';
                        } else if (value == "2") {
                            return '中等破坏';
                        } else if (value == "3") {
                            return '严重破坏';
                        } else if (value == "4") {
                            return '完全破坏';
                        }
                    }
                },
                {
//                  field: 'earthquakeIntensity',
                    title: '地震动强度（%）',
                    colspan: 5,
//                  width: '15%',
                    align: 'center',
                },
//              {
//                  field: 'vulnerability',
//                  title: '易损性',
//                  width: '15%',
//                  align: 'center',
//              },
            ], [
                {field: 'vulnerabilityVI', title: 'VI', width: '10%', align: 'center', editor:{type:'numberbox',options:{precision:2}},
				    formatter:function(val,rowData,rowIndex){
				    	debugger;
				    	if (val != null){
                            var num = new Number(val);
                            return num.toFixed(2);
                        }
				   	}
			    },
                {field: 'vulnerabilityVII', title: 'VII', width: '10%', align: 'center', editor:{type:'numberbox',options:{precision:2}},
				    formatter:function(val,rowData,rowIndex){
				    	debugger;
                        if (val != null){
                            var num = new Number(val);
                            return num.toFixed(2);
                        }
				   	}
			    },
                {field: 'vulnerabilityVIII', title: 'VIII', width: '10%', align: 'center', editor:{type:'numberbox',options:{precision:2}},
				    formatter:function(val,rowData,rowIndex){
                        if (val != null){
                            var num = new Number(val);
                            return num.toFixed(2);
                        }
				   	}
				},
                {field: 'vulnerabilityIX', title: 'IX', width: '10%', align: 'center', editor:{type:'numberbox',options:{precision:2}},
                	formatter:function(val,rowData,rowIndex){
                        if (val != null){
                            var num = new Number(val);
                            return num.toFixed(2);
                        }
				   	}
                },
                {field: 'vulnerabilityX', title: 'X', width: '10%', align: 'center', editor:{type:'numberbox',options:{precision:2}},
                	formatter:function(val,rowData,rowIndex){
                        if (val != null){
                            var num = new Number(val);
                            return num.toFixed(2);
                        }
				   }
               	}
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "模板",
                handler: function () {
                    downloadTemplate();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importForm();
                }
            }, {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
            }],
            onClickCell: function (index, field, value) {
                if (endEditing()) {
                    $('#fxVulnerabilityAreaGrid').datagrid('selectRow', index).datagrid('editCell', {
                        index: index,
                        field: field
                    });
                    editIndex = index;
                    mergeCells("fxVulnerabilityAreaGrid", "area,structureType");
                }
            },
//          onDblClickCell: function (index, field, value) {
//				$("#fxVulnerabilityAreaGrid").datagrid('endEdit', index);
//				debugger;
//				mergeCells("fxVulnerabilityAreaGrid", "area,structureType");
//        	},
            onAfterEdit: function (index, row, changes) {
//             $("#fxVulnerabilityAreaGrid").datagrid('endEdit', index);
//			    $.ajax({
//			        url : '要改变后台数据的controller路径?fieId1='+row.属性1,
//			        data:{fieId2:row.fieId}, //额外的参数
//			        dataType: "text",//响应结果为文本
//			        success:function (data) {
//			            $.messager.alert('消息', data);
//			        }
//			    });
				//console.log(index, row, changes);
                debugger
                if (row.vulnerabilityVI == null && row.vulnerabilityVII == null
                    && row.vulnerabilityVIII == null && row.vulnerabilityIX == null
                    && row.vulnerabilityX == null){
                    Util.alert("数据不能为空！");
                }else {
                    $.ajax({
                        url: getFxVulnerabilityAreaController(),
                        contentType: "application/json",
                        data: JSON.stringify(row),
                        type: "put",
                        success: function (data) {
                            Util.alert(data.message);
                            createFxVulnerabilityAreaGrid();
                        }
                    });
                }
            },
            queryParams: {
                area: $("#areaSelect").val(),
//              structureType: $("#structureTypeSelect").val(),
//              damageDegree: $("#damageDegreeSelect").val(),
            },
            onLoadSuccess: function (data) {

                //垂直合并单元格
                mergeCells("fxVulnerabilityAreaGrid", "area,structureType");
            },
//          pagination: true,
//          pageSize: 10
        });
    };
    $.extend($.fn.datagrid.methods, {
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat(
                    $(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });
    var editIndex = undefined;

    //结束编辑
    function endEditing() {
        if (editIndex == undefined) {
            return true
        }
        if ($('#fxVulnerabilityAreaGrid').datagrid('validateRow', editIndex)) {
            $('#fxVulnerabilityAreaGrid').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };
    //合并单元格方法
    /**
     * EasyUI DataGrid根据字段动态合并单元格
     * @param colList 要合并table的id, 此例子中是tTable
     * @param colList 要合并的列,多个列用逗号分隔(例如："tempParam,flowCode,queryParam");
     */
    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };
    var formValidator = function () {
        $("#fxVulnerabilityAreaForm").validate({
            rules: {
                area: {
                    required: true,
                },
                structureType: {
                    required: true,
                },
                damageDegree: {
                    required: true,
                },
                earthquakeIntensity: {
                    required: true,
                },
                vulnerability: {
                    required: true,
                },
            },
            messages: {
                area: {
                    required: "地区不允许为空!",
                },
                structureType: {
                    required: "结构类型不允许为空!",
                },
                damageDegree: {
                    required: "破坏程度不允许为空!",
                },
                earthquakeIntensity: {
                    required: "地震动强度不允许为空!",
                },
                vulnerability: {
                    required: "易损性不允许为空!",
                },
            }
        });
    };
    var getFxVulnerabilityArea = function (id) {
        $.ajax({
            url: getFxVulnerabilityAreaController() + "/" + id,
            type: "get",
            success: function (data) {
                Tool.deserialize("fxVulnerabilityAreaForm", data);
            }
        });
    };


    // 下载模板
    var downloadTemplate = function () {
        window.location.href = getServer() + "/excel/地区易损性模板.xlsx";
    };

    // 导入
    var importForm = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/地区易损性模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxVulnerabilityAreaController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                }
            });
        });
    };


    // 导出
    var exportForm = function () {
        let area = $("#areaSelect").val();
        window.location.href = getFxVulnerabilityAreaController() + "/export?area=" + area;
    };

    window._editFxVulnerabilityArea = function (fxVulnerabilityAreaId) {
        var slidebar = Util.slidebar({
            url: fxVulnerabilityAreaFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                initAreaSelectFrom();
                initStructureTypeSelectFrom();
                initDamageDegreeSelectFrom();
                initEarthquakeIntensitySelectFrom();
                formValidator();
                getFxVulnerabilityArea(fxVulnerabilityAreaId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxVulnerabilityAreaForm").valid()) {
                        var data = Tool.serialize("fxVulnerabilityAreaForm");
                        $.ajax({
                            url: getFxVulnerabilityAreaController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxVulnerabilityAreaGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteFxVulnerabilityArea = function () {
        var rows = $("#fxVulnerabilityAreaGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxVulnerabilityAreaController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxVulnerabilityAreaGrid();
                }
            });
        }, function () {
            return;
        });

    };

    return {
        init: init
    };
});
